package com.zhihaoliang.coroutine.util

import com.zhihaoliang.coroutine.buss.net.model.User


/*
TODO: Write aggregation code.

 In the initial list each user is present several times, once for each
 repository he or she contributed to.
 Merge duplications: each user should be present only once in the resulting list
 with the total value of contributions for all the repositories.
 Users should be sorted in a descending order by their contributions.

 The corresponding test can be found in test/tasks/AggregationKtTest.kt.
 You can use 'Navigate | Test' menu action (note the shortcut) to navigate to the test.
*/
fun List<User>.aggregate(): List<User> {
    if (isEmpty()) return this

    val hash: MutableMap<String, User> = HashMap()
    for (item in this) {
        val user = hash[item.login]
        if (user == null) {
            hash[item.login] = item
        } else {
            user.contributions += item.contributions
        }
    }

    val list: MutableList<User> = ArrayList()
    for (entry in hash.entries) {
        list.add(entry.value)
    }

    return list.toList().sortedBy { -it.contributions }
}
